#include "astviewmodel.h"

AstViewModel::AstViewModel(QObject *parent) : QJsonModel(parent)
{
}

AstViewModel::AstViewModel(const QString &fileName, QObject *parent) : QJsonModel(fileName, parent)
{
}

AstViewModel::AstViewModel(QIODevice *device, QObject *parent) : QJsonModel(device, parent)
{
}

AstViewModel::AstViewModel(const QByteArray &json, QObject *parent) : QJsonModel(json, parent)
{
}

AstViewModel::~AstViewModel()
{
}

bool AstViewModel::loadJson(const QByteArray &json)
{
    if(!QJsonModel::loadJson(json)){
        QJsonModel::loadJson("{}");
        return false;
    }
    return true;
}

Qt::ItemFlags AstViewModel::flags(const QModelIndex &index) const
{
    int col = index.column();
    auto item = static_cast<QJsonTreeItem *>(index.internalPointer());

    auto isArray = QJsonValue::Array == item->type();
    auto isObject = QJsonValue::Object == item->type();
    return Qt::ItemIsEditable | QAbstractItemModel::flags(index);

    if ((col == 1) && !(isArray || isObject))
    {
        return Qt::ItemIsEditable | QAbstractItemModel::flags(index);
    }
    else
    {
        return QAbstractItemModel::flags(index);
    }
}

QVariant AstViewModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole || role != Qt::EditRole)
        return QVariant();
    if (orientation == Qt::Horizontal)
        return mHeaders.value(section);
    else
        return QVariant();
}

QVariant AstViewModel::data(const QModelIndex &index, int role) const
{

    if (!index.isValid())
        return QVariant();
    QJsonTreeItem *item = static_cast<QJsonTreeItem *>(index.internalPointer());

    if (1 == index.column())
    {
        switch (role)
        {
        case Qt::ForegroundRole:
            if ("type" == item->key())
                return QVariant::fromValue(QColor(Qt::cyan));
        }
    }

    if (Qt::EditRole == role && index.column() == 0)
        return QString("%1").arg(item->key());
    return QJsonModel::data(index, role);
}
